import { ref, onMounted, reactive, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { phone, setProvince } from '../../../utils/validate'
import { useRoute, useRouter } from 'vue-router'
import * as _ from 'lodash'
import {
  getListStore,
  saveStore,
  getListCurrentMothInWidthOutStoreQty,
  deleteStore,
  disableStore,
  canNegativeStock,
  getDetailStore,
  getNetworkEmpAddressPageSelect,
  getNetworkAddressPageSelect,
} from '../../../api/store'
export default function () {
  const loading = ref(false)
  const total = ref(0)
  const tableDataList = ref(null)
  const pagination = ref()
  const ids = ref([])
  const ruleFormRef = ref()
  const addrsDom = ref()
  const addDialog = ref(false)
  const router = useRouter()
  const InWidthOutStoreQty = ref(null)
  const route = useRoute()
  const storeListRef = ref()
  const addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })
  const outStoreRelation = ref([])
  const storeRelatioinSearch = ref() // 服务商/工程师远程搜索关键词
  // 仓库列表搜索对象
  const storeListSearch = ref({
    page: 1,
    limit: 50,
    outStoreExample: null, // 仓库类型：0-内部仓库，1-服务商-外仓库，2-工程师-外仓库
    outStore: null, // 仓库类型：false-内部仓库，true-外部仓库
    outStoreType: null, // 外部仓库类型：1-服务商仓库，2-工程师仓库，当is_out_store=true时生效
    storeSearch: '', // 仓库关键词搜索：仓库名称/仓库编码
    userSearch: '', // 仓库联系人关键词搜索：仓库联系人/手机号
  })
  const storeForm = ref({
    address: '',
    area: '',
    canNegativeStock: false, //是否允许负库存：false-不允许，true-允许
    city: '',
    delStorePositionIds: [], //	删除的仓库仓位ID集合
    enableStorePosition: false, //是否启用仓位：false-不启用，true-启用
    id: null, //
    name: '', //仓库名称
    otherPhone: '', //其他联系方式
    outStoreExample: 0, // 仓库类型：0-内部仓库，1-服务商-外仓库，2-工程师-外仓库
    outStore: false, //仓库类型：false-内部仓库，true-外部仓库
    outStoreType: 1, //外部仓库类型：1-服务商仓库，2-工程师仓库，当is_out_store=true时生效,示例值(1)
    relationId: '', // 关联ID，当is_out_store=1时生效，关联网点或工程师/网点人员ID
    province: '',
    status: true, //	仓库状态：false-启用，true-禁用//取反值渲染
    storeNo: '', //仓库编码，不传则系统生成
    storePositionVos: [
      //仓库仓位对象
      {
        id: null, //仓位ID，新增不必传，修改必传
        name: '', //仓位
        status: false, //仓位状态：false-启用，true-禁用//取反值渲染
      },
    ],
    town: '',
    userName: '',
    userPhone: '',
  })
  const rulesStore = reactive({
    address: [{ required: true, message: '请输入详细地址', trigger: ['blur', 'change'] }],
    name: [{ required: true, message: '请输入仓库名称', trigger: ['blur', 'change'] }], //仓库名称
    outStoreExample: [{ required: true, message: '仓库类型', trigger: 'change' }], //仓库类型：false-内部仓库，true-外部仓库
    userName: [{ required: true, message: '请输入仓库联系人', trigger: ['blur', 'change'] }],
    userPhone: [
      { required: true, message: '请输入联系人手机号', trigger: ['blur', 'change'] },
      { validator: phone(storeForm.value.userPhone), trigger: ['blur', 'change'] },
    ],
    province: [
      {
        required: true,
        validator: setProvince(storeForm.value.province),
        trigger: ['blur', 'change'],
      },
    ],
    relationId: [],
  })
  // 显示添加弹窗
  const showAdd = () => {
    addDialog.value = true
    storeForm.value = {
      address: '',
      area: '',
      canNegativeStock: false, //是否允许负库存：false-不允许，true-允许
      city: '',
      delStorePositionIds: [], //	删除的仓库仓位ID集合
      enableStorePosition: false, //是否启用仓位：false-不启用，true-启用
      id: null, //
      name: '', //仓库名称
      otherPhone: '', //其他联系方式
      outStoreExample: 0, // 仓库类型：0-内部仓库，1-服务商-外仓库，2-工程师-外仓库
      outStore: false, //仓库类型：false-内部仓库，true-外部仓库
      outStoreType: 1, //外部仓库类型：1-服务商仓库，2-工程师仓库，当is_out_store=true时生效,示例值(1)
      relationId: '', // 关联ID，当is_out_store=1时生效，关联网点或工程师/网点人员ID
      province: '',
      status: true, //	仓库状态：false-启用，true-禁用	//取反值渲染
      storeNo: '', //仓库编码，不传则系统生成
      storePositionVos: [
        //仓库仓位对象
        {
          id: null, //仓位ID，新增不必传，修改必传
          name: '', //仓位
          status: false, //仓位状态：false-启用，true-禁用
        },
      ],
      town: '',
      userName: '',
      userPhone: '',
    }
    addrs.value = {
      province: '',
      city: '',
      area: '',
      town: '',
    }
  }

  // 关联服务商/工程师远程搜索
  const onRelationREmoetMethod = _.throttle((keyword: string) => {
    storeRelatioinSearch.value = keyword
  }, 500)

  // 关联服务商/工程师改变事件
  const onRelationChange = (val) => {
    outStoreRelation.value.map((item) => {
      if (item.id == val) {
        storeForm.value.name = storeForm.value.name ? storeForm.value.name : item.name
        storeForm.value.userName = item.username
        storeForm.value.userPhone = item.phone
        storeForm.value.province = item.province
        storeForm.value.city = item.city
        storeForm.value.area = item.area
        storeForm.value.town = item.town
        storeForm.value.address = item.address
        addrs.value = {
          province: item.province,
          city: item.city,
          area: item.area,
          town: item.town,
        }
      }
    })
  }

  // 根据仓库ID获取仓库详情
  const getDetailStoreItem = async (storeId: string) => {
    loading.value = true
    await getDetailStore(storeId).then((res) => {
      if (res) {
        if (res.data.code == 20000) {
          addDialog.value = true
          const data = res.data.data.row
          nextTick(() => {
            storeForm.value = {
              ...data,
              outStoreExample: data.outStore == false ? 0 : data.outStoreType,
            }
            storeForm.value.relationId =
              storeForm.value.relationId === '0' ? '' : storeForm.value.relationId
            storeForm.value.status = !data.status
            storeForm.value.storePositionVos = res.data.data.row.storePositionVos.map((o) => {
              return { ...o, status: !o.status }
            })
            addrs.value = {
              province: res.data.data.row.province,
              city: res.data.data.row.city,
              area: res.data.data.row.area,
              town: res.data.data.row.town,
            }
          })
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 4000,
              offset: 200,
            })
        }
      }
    })
    loading.value = false
  }
  // 获取仓库列表
  const getListStoreRows = () => {
    loading.value = true
    storeListSearch.value.page = pagination.value.current // 当面页码
    storeListSearch.value.limit = pagination.value.size // 当面页码
    if (storeListSearch.value.outStoreExample == 0) {
      storeListSearch.value.outStore = false
    }
    if (storeListSearch.value.outStoreExample > 0) {
      storeListSearch.value.outStore = true
      storeListSearch.value.outStoreType = storeListSearch.value.outStoreExample
    }
    getListStore(storeListSearch.value).then((res) => {
      if (res) {
        if (res.data.code == 20000) {
          tableDataList.value = res.data.data.rows
          total.value = Number(res.data.data.total)
          getCurrentMothInWidthOutStoreQty()
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 4000,
              offset: 200,
            })
        }
      }
      loading.value = false
    })
  }
  // 获取仓库列表本月的入-出库的数量
  const getCurrentMothInWidthOutStoreQty = () => {
    getListCurrentMothInWidthOutStoreQty().then((res) => {
      if (res) {
        InWidthOutStoreQty.value = res.data.data
      }
    })
  }
  // 批量删除、启用、禁用
  async function changeAll(n: number, str: string) {
    if (ids.value.length == 0) {
      ElMessage({
        message: `请先选择要操作的选项`,
        type: 'warning',
        duration: 2000,
        offset: 200,
      })
      return
    }
    ElMessageBox({
      title: '提示',
      message: `确定${str}?`,
      showCancelButton: true,
      closeOnClickModal: false,
      type: n === 3 ? 'error' : 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
    })
      .then(async () => {
        loading.value = true
        switch (n) {
          case 1:
          case 2:
            await disableStore(ids.value, n == 1 ? false : true).then((res) => {
              if (res) {
                if (res.data.isError)
                  ElMessage({
                    showClose: true,
                    message: res.data.message,
                    type: res.data.success ? 'success' : 'error',
                    offset: 200,
                  })
                if (res.data.code == 20000) {
                  ids.value = []
                  getListStoreRows()
                }
              }
              loading.value = false
            })
            break
          case 3:
            await deleteStore(ids.value).then((res) => {
              if (res) {
                if (res.data.isError)
                  ElMessage({
                    showClose: true,
                    message: res.data.message,
                    type: res.data.success ? 'success' : 'error',
                    offset: 200,
                  })
                if (res.data.code == 20000) {
                  if (addDialog.value) {
                    addDialog.value = false
                  }
                  ids.value = []
                  getListStoreRows()
                }
              }
              loading.value = false
            })
            break
          case 4:
          case 5:
            await canNegativeStock(ids.value, n == 4 ? true : false).then((res) => {
              if (res) {
                if (res.data.isError)
                  ElMessage({
                    showClose: true,
                    message: res.data.message,
                    type: res.data.success ? 'success' : 'error',
                    offset: 200,
                  })
                if (res.data.code == 20000) {
                  ids.value = []
                  getListStoreRows()
                }
              }
              loading.value = false
            })
            break
        }
      })
      .catch()
  }
  // 保存添加仓库
  const submitForm = _.debounce(async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid) => {
      if (valid) {
        if (storeForm.value.outStoreExample == 0) {
          storeForm.value.outStore = false
        }
        if (storeForm.value.outStoreExample > 0) {
          storeForm.value.outStore = true
          storeForm.value.outStoreType = storeForm.value.outStoreExample
        }
        if (storeForm.value.enableStorePosition && storeForm.value.storePositionVos.length == 0) {
          ElMessage.warning('至少添加一个仓位！')
          return
        }
        storeForm.value.status = !storeForm.value.status
        if (storeForm.value.enableStorePosition) {
          storeForm.value.storePositionVos = storeForm.value.storePositionVos.map((o) => {
            return { ...o, status: !o.status }
          })
        }

        loading.value = true
        saveStore(storeForm.value).then((res) => {
          if (res) {
            if (res.data.isError)
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: res.data.success ? 'success' : 'error',
                offset: 200,
              })
            if (res.data.code == 20000) {
              getListStoreRows()
              closeClick()
            }
          }
          loading.value = false
        })
      }
    })
  }, 600)
  // 选择批量操作的id
  function handleChange(val) {
    ids.value = []
    val.filter((o) => {
      ids.value.push(o.id)
    })
  }
  // 关闭取消
  const closeClick = () => {
    if (!ruleFormRef.value) return
    ruleFormRef.value.resetFields()
    addDialog.value = false
  }
  // 所属地址
  function addressValChange() {
    addrs.value = addrsDom.value.getSelectAddr()
    storeForm.value.province = addrs.value.province
    storeForm.value.city = addrs.value.city
    storeForm.value.area = addrs.value.area
    storeForm.value.town = addrs.value.town
  }
  // 删除仓库
  const deleteClick = () => {
    storeForm.value.id
    ids.value = [storeForm.value.id]
    changeAll(3, '要删除仓库')
  }
  // 重置
  function clearVlaue() {
    storeListSearch.value = {
      page: 1,
      limit: 50,
      outStoreExample: null,
      outStore: null, // 仓库类型：false-内部仓库，true-外部仓库
      outStoreType: null, // 外部仓库类型：1-服务商仓库，2-工程师仓库，当is_out_store=true时生效
      storeSearch: '', // 仓库关键词搜索：仓库名称/仓库编码
      userSearch: '', // 仓库联系人关键词搜索：仓库联系人/手机号
    }
    getListStoreRows()
  }
  // 仓库详情
  const goDetailPage = (row) => {
    router.push('/storage/detail/' + row.id)
  }
  // 添加仓库仓位
  const addItem = () => {
    storeForm.value.storePositionVos.push({
      id: null, //仓位ID，新增不必传，修改必传
      name: '', //仓位
      status: false, //仓位状态：false-启用，true-禁用
    })
    storeListRef.value.scrollTop = storeListRef.value.scrollHeight
  }
  // 删除仓库位
  const deleteItem = (i, index) => {
    if (storeForm.value.storePositionVos.length == 1) {
      ElMessage.warning('必须保留至少一个仓位！')
      return
    }
    if (!storeForm.value.delStorePositionIds) {
      storeForm.value.delStorePositionIds = []
    }

    storeForm.value.storePositionVos = storeForm.value.storePositionVos.filter((o, n) => {
      if (index == n && i.id) {
        storeForm.value.delStorePositionIds.push(i.id)
      }
      return n !== index
    })
  }
  // 监听仓库位是否开启
  const enableStorePositionValue = (n) => {
    if (n) {
      storeForm.value.storePositionVos = [
        {
          id: null, //仓位ID，新增不必传，修改必传
          name: '', //仓位
          status: false, //仓位状态：false-启用，true-禁用
        },
      ]
    } else {
      storeForm.value.storePositionVos = []
    }
  }
  // 监听仓库类型是否外部仓库
  watch(
    () => storeForm.value.outStoreExample,
    () => {
      if (!storeForm.value.id) {
        storeForm.value.relationId = ''
      }
      if (!storeForm.value.outStoreExample) {
        return
      }
      rulesStore.relationId = [{ required: false }]
      if (storeForm.value.outStoreExample === 1) {
        getNetworkAddressPageSelectApi()
        rulesStore.relationId = [
          { required: true, message: '请选择服务商', trigger: ['change', 'blur'] },
        ]
        return
      }
      if (storeForm.value.outStoreExample === 2) {
        getNetworkEmpAddressPageSelectApi()
        rulesStore.relationId = [
          { required: true, message: '请选择工程师', trigger: ['change', 'blur'] },
        ]
        return
      }
    },
  )
  // 监听服务商/工程师关键词搜索
  watch(
    () => storeRelatioinSearch.value,
    (n, o) => {
      if (n == '' && !o) {
        return
      }
      if (storeForm.value.outStoreExample === 1) {
        getNetworkAddressPageSelectApi()
        return
      }
      if (storeForm.value.outStoreExample === 2) {
        getNetworkEmpAddressPageSelectApi()
      }
    },
  )

  // 获取服务商及地址接口Api
  const getNetworkAddressPageSelectApi = () => {
    getNetworkAddressPageSelect({ name: storeRelatioinSearch.value }).then((res) => {
      outStoreRelation.value = res.data.data.rows
    })
  }
  // 获取工程师及地址接口Api
  const getNetworkEmpAddressPageSelectApi = () => {
    getNetworkEmpAddressPageSelect({ name: storeRelatioinSearch.value }).then((res) => {
      outStoreRelation.value = res.data.data.rows
    })
  }

  onMounted(() => {
    getListStoreRows()
  })

  return {
    handleChange,
    getListStoreRows,
    deleteClick,
    showAdd,
    addressValChange,
    enableStorePositionValue,
    changeAll,
    closeClick,
    getDetailStoreItem,
    submitForm,
    ruleFormRef,
    addItem,
    deleteItem,
    storeListRef,
    addDialog,
    addrs,
    addrsDom,
    storeForm,
    clearVlaue,
    goDetailPage,
    rulesStore,
    InWidthOutStoreQty,
    loading,
    total,
    pagination,
    tableDataList,
    storeListSearch,
    ids,
    outStoreRelation,
    onRelationChange,
    onRelationREmoetMethod,
  }
}
